module DataStorage (loadItems, getItem, addItem, saveItems) where

import Data.List
import System.IO
import System.Directory
--import System.FilePath
import GenericFunctions

-- Function used to load all items from the specified file
loadItems fname =   do  System.Directory.createDirectoryIfMissing True "data/"
                        hFile <- openFile (createFname fname) ReadWriteMode
                        idata <- loadData hFile
                        hClose hFile
                        return idata
                        
-- Function used to add a new item to the specified file
addItem i fname =   do  appendFile (createFname fname) (show i)
                        appendFile (createFname fname) "\n"
                        
-- Function used to save all items in the specified file
saveItems i fname = do  hFile <- openFile (createFname fname) WriteMode                        
                        hClose hFile
                        mapM_ ((flip addItem) fname) i
                        
-- Function used to get certain item in the specified file
getItem f fname =   do  items <- loadItems fname
                        return $ find f items

-- Function used to get all data from the file                            
loadData hFile =    do  isEof <- hIsEOF hFile
                        if isEof then
                            return []
                        else do
                            line <- hGetLine hFile
                            rest <- (loadData hFile)
                            return ([(read line)] ++ rest)
                            
-- Function used to build a file path with certain data
createFname fname = ("data/" ++ fname ++ ".data")
